﻿Imports System
Imports System.Collections
Imports System.Transactions

Namespace System.Workflow.Runtime
    Friend NotInheritable Class VolatileResourceManager
        ' Methods
        Friend Sub New()
        End Sub

        Friend Sub ClearAllBatchedWork()
            If (Not Me._workCollection Is Nothing) Then
                Me._workCollection.RollbackAllBatchedWork
            End If
        End Sub

        Friend Sub Commit()
            Me._mergedBatch = Me.GetMergedBatch
            Dim current As Transaction = Transaction.Current
            If (Nothing Is current) Then
                Throw New InvalidOperationException(ExecutionStringManager.NullAmbientTransaction)
            End If
            Me._mergedBatch.Commit(current)
        End Sub

        Friend Sub Complete()
            Try 
                Me._mergedBatch.Complete(True)
            Finally
                If (Not Me._mergedBatch Is Nothing) Then
                    Me._mergedBatch.Dispose
                    Me._mergedBatch = Nothing
                End If
                If (Not Me._workCollection Is Nothing) Then
                    Me._workCollection.ClearSubBatches
                End If
            End Try
        End Sub

        Private Function GetMergedBatch() As WorkBatch
            Return Me._workCollection.GetMergedBatch
        End Function

        Friend Sub HandleFault()
            If (Not Me._mergedBatch Is Nothing) Then
                Me._mergedBatch.Dispose
                Me._mergedBatch = Nothing
            End If
            If (Not Me._workCollection Is Nothing) Then
                Me._workCollection.ClearTransientBatch
            End If
        End Sub


        ' Properties
        Friend ReadOnly Property BatchCollection As WorkBatchCollection
            Get
                Return Me._workCollection
            End Get
        End Property

        Friend ReadOnly Property IsBatchDirty As Boolean
            Get
                Dim enumerator As IDictionaryEnumerator = Me._workCollection.GetEnumerator
                Do While enumerator.MoveNext
                    Dim batch As WorkBatch = DirectCast(enumerator.Value, WorkBatch)
                    If batch.IsDirty Then
                        Return True
                    End If
                Loop
                Return False
            End Get
        End Property


        ' Fields
        Private _mergedBatch As WorkBatch
        Private _workCollection As WorkBatchCollection = New WorkBatchCollection
    End Class
End Namespace

